package com.database;

import java.util.HashMap;

import database.databaseInteraction;
import database.database_auth;

import database.databaseInteraction;
import database.database_auth;

/** a base-class for database entries **/
public class databaseElement
{
	public String tableName = ""; // the table that is operated on
	public String ID = ""; // a unique ID that identifies an element in database, even if the element is associated with multiple records in the database
	public String IDKEY = ""; // where is the UNIQUE ID key in the table, every element that is associated with multiple records shares the same ID (a integer number)
	
	public static databaseInteraction DatabaseConnection = new databaseInteraction();
	public static database_auth database_auth_inst = new database_auth(); // will be read from configuration file endpoint_xml.config -> host,port,DatabaseName,type,TableName,user,password
	
	public databaseElement(database_auth database_auth_inst, String tableName, String IDKEY)
	{
		this.tableName = tableName;
		this.IDKEY = IDKEY;
	}

	/**
	 * generate new ID by really checking what IDs there are and returning one that is not used
	 * (more resource intensive approach than auto increment of MySQL)
	 */
	
	public String generateNewID(database_auth database_auth_inst, String tableName, String IDKEY)
	{
		int CURRENT_ID = 0; 

		String question = "SELECT * FROM `"+tableName+"`;"; // mysql function to generate passsword hash: SELECT PASSWORD('djfkldjfkld!');
	
		DatabaseConnection.askDatabase(database_auth_inst, question); // StringBuffer answer = DatabaseConnection.askDatabase( host, DatabaseName, TableName, user, password, question);
		
        /** start with 1... and stop when a number can not be found in the list **/
		int UNIQUE_MESSAGEID = 1;

		boolean is_unique = true;

		/** iterate over ArrayList answerJava and check if UNIQUE_MESSAGEID is really not used yet **/
	    int LENGTH = DatabaseConnection.answerJAVA.size();
	    for(int counter = 0;counter < LENGTH;counter++)
	    {
	    	HashMap element = (HashMap) DatabaseConnection.answerJAVA.get(counter);
	    	if(element.get(IDKEY).equals(Integer.toString(UNIQUE_MESSAGEID)))
	    	{
	    		is_unique = false;
	    		// restart with new value
	    		counter = 0;
	    		UNIQUE_MESSAGEID++;
	    	}
	    }

	    ID = Integer.toString(UNIQUE_MESSAGEID);
	    
	    return Integer.toString(UNIQUE_MESSAGEID);
	}
}
